package com.example.common.config;

import org.springframework.stereotype.Component;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.OperationBuilderPlugin;
import springfox.documentation.spi.service.contexts.OperationContext;
import springfox.documentation.service.Parameter;


import java.util.List;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.ArrayList;

@Component
public class ParameterOrderingPlugin implements OperationBuilderPlugin {

    @Override
    public void apply(OperationContext context) {
        List<Parameter> parameters = context.operationBuilder().build().getParameters();
        Map<String, Parameter> parameterMap = new LinkedHashMap<>();

        // 先添加 ID 参数
        parameters.stream()
                .filter(param -> "id".equals(param.getName()))
                .findFirst()
                .ifPresent(idParam -> {
                    parameterMap.put("id", idParam);
                    parameters.remove(idParam);
                });

        // 添加其他参数
        parameters.forEach(param -> parameterMap.put(param.getName(), param));

        // 更新操作
        context.operationBuilder().parameters(new ArrayList<>(parameterMap.values()));
    }

    @Override
    public boolean supports(DocumentationType delimiter) {
        return DocumentationType.SWAGGER_2.equals(delimiter);
    }
}
